package com.qm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qm.mapper.ItemDescMapper;
import com.qm.pojo.Item;
import com.qm.pojo.ItemDesc;
import com.qm.service.ItemService;
import com.qm.vo.LayUITable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.qm.mapper.ItemMapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service
public class ItemServiceImpl implements ItemService {
	
	@Autowired
	private ItemMapper itemMapper;

	@Autowired
	private ItemDescMapper itemDescMapper;

	@Override
	public LayUITable findItemByPage(Integer page, Integer rows) {
//		long total = itemMapper.selectCount(null);
//		int startIndex = (page-1) * rows;
//		List<Item> pageList = itemMapper.findItemByPage(startIndex, rows);
//		return new LayUITable(total,pageList);

		//1.通过分页对象 将page rows 进行参数封装
		IPage iPage = new Page(page, rows);
		QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
		queryWrapper.orderByDesc("updated");
		//2.通过iPage对象封装其他的分页数据
		iPage = itemMapper.selectPage(iPage, queryWrapper);
		long total = iPage.getTotal();
		List<Item> itemList = iPage.getRecords();
		return new LayUITable(total, itemList);
	}

	@Transactional	//表示方式使用事务控制
	@Override
	public void saveItem(Item item, ItemDesc itemDesc) {
		//主键自增 入库之后才有主键
		//利用Mybatis的主键自动回显的功能实现...
		item.setStatus(1);	//设定启动状态
		itemMapper.insert(item);
		//商品详情表的主键应该与商品表中的主键一致
		itemDesc.setItemId(item.getId());
		itemDescMapper.insert(itemDesc);
	}

	@Override
	public void updateItem(Item item,ItemDesc itemDesc) {
		itemMapper.updateById(item);
		itemDesc.setItemId(item.getId());
		itemDescMapper.updateById(itemDesc);

	}

	@Override
	public void deleteItems(Long[] ids) {
		itemMapper.deleteIds(ids);
		//删除商品详情信息
		List<Long> idList = Arrays.asList(ids);
		itemDescMapper.deleteBatchIds(idList);
	}

	@Override
	public void updateStatus(Integer status, Long[] ids) {
		Item item = new Item();
		item.setStatus(status);
		UpdateWrapper updateWrapper = new UpdateWrapper();
		List<Long> idList = Arrays.asList(ids);
		updateWrapper.in("id",idList);
		itemMapper.update(item,updateWrapper);
	}

	@Override
	public ItemDesc findItemDescById(Long id) {
		return itemDescMapper.selectById(id);
	}

	@Override
	public Item findItemById(Long id) {
		return itemMapper.selectById(id);
	}


}
